﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Gollie.Extensions;
namespace Gollie.Controls
{
	public partial class NumericTextBox : BaseUserControl
	{
		protected override void PreLoadHandler(object sender, EventArgs e)
		{
			string jsCall = "return FilterNumeric(this, event, " + (AllowNegative ? "true);" : "false);");
			string jsCall2 = "ReStyle(this, event, " +
							(AllowNegative ? "true" : "false") +
							"," +
							PositiveText.SingleQuote() +
							"," +
							NegativeText.SingleQuote() +
							"," +
							TextControlId.SingleQuote() +
							");";
			
			this.TextBox1.Attributes.Add("onkeypress", jsCall);
			this.TextBox1.Attributes.Add("onkeyup", jsCall2);
		}

		public TextBox TextBox
		{
			get { return this.TextBox1; }
		}	

		public decimal DecimalValue
		{
			get
			{
				string s = Text.Replace('.', ',');
				int commaCount = s.Count(p => p == ',');
				if (commaCount > 1)
					throw new FormatException();

				decimal val;
				if (decimal.TryParse(s, out val) == false)
					throw new FormatException();

				return val;
			}
		}

		public int IntValue
		{
			get
			{
				int val;

				if (int.TryParse(Text, out val) == false)
					throw new FormatException();

				return val;
			}
		}

		public string Text
		{
			get { return this.TextBox.Text; }
			set { this.TextBox.Text = value; }
		}

		public string ToolTip
		{
			get { return this.TextBox.ToolTip; }
			set { this.TextBox.ToolTip = value; }
		}

		public Unit Width
		{
			get { return this.TextBox.Width; }
			set { this.TextBox.Width = value; }
		}

		public bool AllowNegative
		{
			get;
			set;
		}

		public string PositiveText
		{
			get;
			set;
		}

		public string NegativeText
		{
			get;
			set;
		}

		public string TextControlId
		{
			get;
			set;
		}
	}
}